package com.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 三个线程，按照顺序执行——多个线程互斥，有序
 */
public class DataLockConditonOrder {
    int flag=0;
    Lock lock=new ReentrantLock();
    Condition condition1=lock.newCondition();
    Condition condition2=lock.newCondition();
    Condition condition3=lock.newCondition();
    void main(int order)
    {
        lock.lock();

        try{
            //没有轮到1执行
            if (flag!=0)
            {
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //轮到1执行
            for(int i=0;i<10;i++)
            {
                System.out.println("主线程："+Thread.currentThread().getName()+"第"+order+"次循环输出"+i);
            }
            flag=1;
            condition2.signal();
        }
        finally {
            lock.unlock();
        }

    }
    void  sub1(int order)
    {
        lock.lock();
        try{
            //没有轮到2执行
            if(flag!=1)
            {
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //轮到2执行
            for(int i=0;i<20;i++)
            {
                System.out.println("sub1线程："+Thread.currentThread().getName()+"第"+order+"次循环输出"+i);
            }
            flag=2;
            condition3.signal();
        }
        finally {
            lock.unlock();
        }


    }
    void  sub2(int order)
    {
        lock.lock();
        //没有轮到3执行
        try{
            if (flag!=2)
            {
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //轮到3执行
            for(int i=0;i<30;i++)
            {
                System.out.println("sub2线程："+Thread.currentThread().getName()+"第"+order+"次循环输出"+i);
            }
            flag=0;
            condition1.signal();
        }
        finally {
            lock.unlock();
        }


    }


}
